from typing import cast

from src.graph.talent_model import Talent
from src.graph.types import State

def get_state(agent_code: str, thread_id: str) -> State:
    """获取上下文"""
    from src.server.app import get_graph_by_agent_code  # 循环依赖了，延迟导入
    graph = get_graph_by_agent_code(agent_code)
    state = graph.get_state({"configurable": {"thread_id": thread_id}})
    return state


def get_talent_pool(state: State) -> list[Talent]:
    """获取完整人才库列表。"""
    return state.talent_pool

def get_talent_by_id(state: State, talent_id: str) -> Talent | None:
    """根据 ID 查找人才对象。"""
    for talent in state.talent_pool:
        if talent.id == talent_id:
            return talent
    return None

def get_talent_by_name(state: State, name: str) -> Talent | None:
    """根据 姓名 查找人才对象。"""
    for talent in state.talent_pool:
        talent = cast(Talent, talent)
        if talent.name == name:
            return talent
    return None

def update_talent_by_id(state: State, talent_id: str, updates: dict) -> bool:
    """
    根据 ID 更新某个人才对象的部分字段。
    updates 参数示例：{"得分": 88, "面试记录url": "http://..."}
    """
    for i, talent in enumerate(state.talent_pool):
        talent = cast(Talent, talent)
        if talent.id == talent_id:
            for key, value in updates.items():
                if hasattr(talent, key):
                    setattr(talent, key, value)
            state.talent_pool[i] = talent
            return True
    return False

def update_talent_by_name(state: State, name: str, updates: dict) -> bool:
    """
    根据 name 更新某个人才对象的部分字段。
    """
    for i, talent in enumerate(state.talent_pool):
        talent = cast(Talent, talent)
        if talent.name == name:
            for key, value in updates.items():
                if hasattr(talent, key):
                    setattr(talent, key, value)
            state.talent_pool[i] = talent
            return True
    return False

def update_talent_pool(state: State, new_pool: list[Talent]):
    """替换整个人才库。"""
    state.talent_pool = new_pool